package com.it.octoo.conf;

import com.it.octoo.source.CustomerSecurityMetadataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Collections;

/**
 * <p>
 * 说明
 * </p >
 *
 * @author miaoxiao
 * @since 2020/3/26
 */
@Configuration
@EnableWebSecurity
public class OctooWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    /** 必须交由spring管理，初始化权限信息 **/
    @Autowired
    private CustomerSecurityMetadataSource customerSecurityMetadataSource;

    private final static String[] MATCHERS = new String[]{
            "/resources/**", "/actuator/**", "/swagger-ui.html"
            , "/v2/api-docs", "/doc.html", "/webjars/**", "/swagger-resources"
            , "/error"
    };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic()
                .and()
                .cors().configurationSource(corsConfigurationSource())
                .and()
                .csrf().disable().authorizeRequests().anyRequest().authenticated()
                .withObjectPostProcessor(withObjectPostProcessor())
                .and()
                .formLogin().loginProcessingUrl("/login")
                .permitAll()
                .and()
                .logout()
                .deleteCookies("JSESSIONID")
                .logoutUrl("/logout")
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers(MATCHERS);
    }

    /**
     * 跨域配置
     * @return UrlBasedCorsConfigurationSource
     */
    public UrlBasedCorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return source;
    }

    /**
     * 设置使用RoleVoter 选举
     * @return ObjectPostProcessor
     */
    public ObjectPostProcessor<FilterSecurityInterceptor> withObjectPostProcessor(){
        return new ObjectPostProcessor<FilterSecurityInterceptor>() {
            @Override
            public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                o.setSecurityMetadataSource(customerSecurityMetadataSource);
                o.setAccessDecisionManager(new AffirmativeBased(Collections.singletonList(new RoleVoter())));
                return o;
            }
        };
    }
}
